<template>
  <base-container>
    <!-- 搜索栏 -->
    <avue-table-search
      :option="searchOption"
      v-model="searchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />

    <base-table-card>
      <!-- 顶部：公告类目 Tabs（由接口返回） -->
      <template #header-left>
        <el-tabs v-model="activeCategoryId" @tab-change="handleCategoryChange">
          <el-tab-pane
            v-for="c in categoryTabs"
            :key="c.id"
            :name="c.id"
            :label="`${c.categoryName}(${c.messageCount})`"
          />
        </el-tabs>
      </template>

      <template #header-right>
        <el-button type="primary" @click="openAddDialog">新增公告</el-button>
      </template>

      <avue-crud
        ref="crudRef"
        :option="tableOption"
        :data="tableData"
        v-model="formData"
        :page="page"
        :table-loading="tableLoading"
        @refresh-change="loadGetTableData"
        @current-change="loadTablePageChange"
        @size-change="loadTablePageSizeChange"
        @row-save="loadAdd"
        @row-update="loadEdit"
      >
        <!-- 操作列 -->
        <template #menu="{ row }">
          <el-button type="primary" text @click="openEditDialog(row)">编辑</el-button>

          <!-- 展示状态：展示中 -> 隐藏 -->
          <el-button v-if="canHide(row)" type="primary" text @click="confirmHide(row)"> 隐藏 </el-button>

          <!-- 展示状态：已隐藏 -> 展示 -->
          <el-button v-if="canShow(row)" type="primary" text @click="confirmShow(row)"> 展示 </el-button>

          <!-- 手动/发送失败 -> 发送 -->
          <el-button v-if="canSend(row)" type="primary" text @click="confirmSend(row)"> 发送 </el-button>

          <el-button type="text" text @click="loadDel(row)">删除</el-button>
        </template>
      </avue-crud>
    </base-table-card>
  </base-container>
</template>

<script setup>
  import Option from "@/crudOption/message/list";
  import { router } from "@/router/index";
  import { ElMessageBox } from "element-plus";

  /* ============== 顶部 Tabs（公告类目） ============== */
  const categoryTabs = ref([]); // [{ id, categoryName, messageCount }]
  const activeCategoryId = ref(""); // 当前选中的类目 id

  function normalizeCategories(rows) {
    return (rows || [])
      .filter(r => r && r.id != null)
      .map(r => ({
        id: String(r.id),
        categoryName: r.categoryName ?? "",
        messageCount: Number(r.messageCount ?? 0),
      }));
  }

  /** 只负责拿 tabs，不在同一个 try 里拉列表 */
  async function loadCategoryTabs() {
    try {
      const res = await Api.message.StatisticsMsg({});
      const arr = Array.isArray(res?.data) ? res.data : Array.isArray(res) ? res : [];
      categoryTabs.value = normalizeCategories(arr);
      // 若没有选中项，则选第一个
      if (!activeCategoryId.value) activeCategoryId.value = categoryTabs.value[0]?.id ?? "";
    } catch (e) {
      console.error("[StatisticsMsg] error:", e);
      if (categoryTabs.value.length === 0) {
        categoryTabs.value = [];
        activeCategoryId.value = "";
      }
    }
  }

  /* ============== CRUD Hook ============== */

  function openAddDialog() {
    router.push({ name: "AddNotice" });
  }
  function openEditDialog(row) {
    router.push({ name: "AddNotice", query: { id: row.id } });
  }

  let {
    data: tableData,
    loading: tableLoading,
    page,
    search: searchParams,
    form: formData,
    get: loadGetTableData,
    add: loadAdd,
    edit: loadEdit,
    del: loadDel,
    pageNumChange: loadTablePageChange,
    pageSizeChange: loadTablePageSizeChange,
    searchReset: loadTableSearchReset,
    searchChange: loadTableSearch,
  } = useCrudHook({
    get: Api.message.GetmsgList,
    del: Api.message.DelMsg,
    search: { categoryType: "ANNOUNCEMENT" },
    getParamsFormat: params => {
      const p = { ...params };
      // ★ 必传：当前 Tab 的 categoryId
      if (activeCategoryId.value) p.categoryId = activeCategoryId.value;

      const split = (arr, [s, e]) => {
        if (Array.isArray(arr) && arr.length === 2) {
          p[s] = arr[0];
          p[e] = arr[1];
        }
      };
      split(p.createTime, ["saveBeginDate", "saveEndDate"]);
      delete p.createTime;
      split(p.sendTime, ["sendBeginDate", "sendEndDate"]);
      delete p.sendTime;
      split(p.updateTime, ["updateBeginDate", "updateEndDate"]);
      delete p.updateTime;
      return p;
    },
  });

  const { searchOption, tableOption } = Option(formData);

  /* ============== 状态判断（基于枚举） ============== */
  const U = v => (v == null ? "" : String(v).toUpperCase());

  function sendStatusOf(row) {
    // 后端字段：sendStatus ∈ { INIT, PROCESS, SUCCESS, FAIL }
    return U(row.sendStatus || row.status);
  }
  function showStatusOf(row) {
    // 后端字段：displayStatus ∈ { SHOW, HIDE }
    return U(row.displayStatus || row.showStatus || row.display);
  }

  function isSent(row) {
    return sendStatusOf(row) === "SUCCESS";
  }
  function isSendFailed(row) {
    return sendStatusOf(row) === "FAIL";
  }
  function isShown(row) {
    return showStatusOf(row) === "SHOW";
  }
  function isHidden(row) {
    return showStatusOf(row) === "HIDE";
  }

  /** 显隐条件（按你的需求） */
  function canHide(row) {
    // 已发送 且 当前为展示 -> 可隐藏
    return isShown(row);
  }
  function canShow(row) {
    // 已发送 且 当前为隐藏 -> 可展示
    return isHidden(row);
  }
  function canSend(row) {
    // 手动发送 或 发送失败 -> 可发送
    const sendType = U(row.sendType); // 约定: NOW / MANUAL / TIMING
    return sendType === "MANUAL" || isSendFailed(row);
  }

  /* ============== 操作：隐藏 / 展示 / 发送 / 删除 ============== */

  async function confirmHide(row) {
    await ElMessageBox.confirm("确定要隐藏该公告吗？隐藏后将不被展示，用户可能查看不到。", "提示", { type: "warning" });
    await Api.message.ShowOrHideMsg({ id: row.id, status: "HIDE" });
    $msg.success("已隐藏");
    await Promise.all([loadGetTableData(), loadCategoryTabs()]);
  }

  async function confirmShow(row) {
    await ElMessageBox.confirm("确定要展示该公告吗？展示后将被展示，用户能查看。", "提示", { type: "info" });
    await Api.message.ShowOrHideMsg({ id: row.id, status: "SHOW" });
    $msg.success("已展示");
    await Promise.all([loadGetTableData(), loadCategoryTabs()]);
  }

  async function confirmSend(row) {
    await ElMessageBox.confirm("确定要立即重新发送该公告吗？", "提示", { type: "warning" });
    await Api.message.SendMsg({ id: row.id });
    $msg.success("已触发发送");
    await Promise.all([loadGetTableData(), loadCategoryTabs()]);
  }

  /* ============== 行为 ============== */
  function handleCategoryChange() {
    page.currentPage = 1;
    loadGetTableData().catch(err => {
      console.error("[GetmsgList] error:", err);
    });
  }

  /* ============== 挂载 & 监听 ============== */
  onMounted(() => {
    loadCategoryTabs();
  });

  // 当 activeCategoryId 变化（含首次赋值）时取列表
  watch(activeCategoryId, id => {
    if (!id) {
      tableData.value = [];
      return;
    }
    loadGetTableData().catch(err => console.error("[GetmsgList] error:", err));
  });
</script>

<style lang="scss" scoped></style>
